<?php

// 上次订单
class GoodsorderAction extends UserAction
{
    //魔术方法
    public function __construct()
    {
        parent::__construct();
    }

    //订单列表
    public function index()
    {
        $where['user_id'] = $this->uid;
        if (isset($_REQUEST['order_state'])) {
            if ($_REQUEST['order_state'] != 'all') {
                if ($_REQUEST['order_state'] == 3) {//已完成
                    $where['pay_status'] = 2;// 支付状态；0，未付款；1，付款中 ；2，已付款
                    // $where[''] = 2;//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
                    //退货的也在已完成
                    $where['_string'] = "shipping_status=2 or (shipping_status=1 and order_status in ('2','3','4'))";//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
                } else if ($_REQUEST['order_state'] == 1) {
                    $where['pay_status'] = 2;// 支付状态；0，未付款；1，付款中 ；2，已付款
                    $where['shipping_status'] = array('in', '0,3');//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
                    $where['order_status'] = array('in', '1,0');//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
                    //$where['shipping_status'] =1;//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
                } else if ($_REQUEST['order_state'] == 2) {
                    $where['pay_status'] = 2;// 支付状态；0，未付款；1，付款中 ；2，已付款
                    $where['shipping_status'] = 1;//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
                    $where['order_status'] = 1;//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
                    //$where['shipping_status'] =1;//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
                } else {
                    $where['pay_status'] = $_REQUEST['order_state'];
                }
            }
        } else {
            $_GET['order_state'] = 'all';
        }
        $where['user_del'] = 0;
        $p = $_REQUEST['p'];
        $pagesize = 10;
        $p = !empty($p) ? $p : 1;
        $start = ($p - 1) * $pagesize;
        $field = "order_id,order_sn,order_status,shipping_status,pay_status,goods_amount,order_amount,shipping_fee,add_time,consignee,mobile,address";
        $order_model = M('g_order_info');
        $list = $order_model->where($where)//
        ->field($field)->limit($start, $pagesize)->order('order_id desc')->select();
        // echo $order_model->getlastsql();die;
        //订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；--order
        //商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中---shipping
        //支付状态；0，未付款；1，付款中 ；2，已付款----pay
        //待付款 0.0.(0,1)  待发货 0.0.2 待收货0.(1,3).2 已完成1.2.2 退货/返修
//        var_dump($list);die;
        //$order_state = array('0' => '已取消', '10' => '待付款', '20' => '已付款', '30' => '已完成');
        $order_state =array('0' => '已取消', '1' => '待付款', '2' => '待发货','3'=>'已发货', '4' => '已完成');
        $g_order_goods_refund = M('g_order_goods_refund');

        foreach ($list as $key => $value) {
            $order_goods = M('g_order_goods')->field('rec_id,goods_name,goods_image,goods_price,goods_id,yes_refund,is_refund,is_upgrade,goods_number')
                ->where(array('order_id' => $value['order_id']))->select();

            $order_show = $this->get_order_status($value);
            $list[$key]['order_state'] = $order_show['code'];
            $list[$key]['order_state_name'] = $order_show['name'];
            $list[$key]['add_time'] = date("Y/m/d", $value['add_time']);
            $list[$key]['goods'] = $order_goods;
            $list[$key]['is_refund'] = 0;///该订单是否可退货
            $list[$key]['rec_id'] = 0;///该订单是否可退货产品
            //
            $num=0;
            foreach ($order_goods as $k=>$v){
                $num+=$v['goods_number'];
            }
            $list[$key]['num']=$num;
            $list[$key]['order_amount'] += $list[$key]['shipping_fee'];
            $list[$key]['ref_all'] = 0;

            $countgoods = 0;
            if ($order_show['code'] == 'delivered') {
                foreach ($order_goods as $keys => $val) {
                    if ($val['is_refund']) {//可退货
                        if (empty($val['yes_refund'])) {//未退货
                            $list[$key]['is_refund'] = 1;///该订单是否可退货
                            $countgoods++;
                            $list[$key]['rec_id'] = $val['rec_id'];///该订单可退货产品
                            if ($countgoods > 1) {
                                $list[$key]['rec_id'] = 0;///包含2个产品 取消快捷连接
                            }
                        }
                    }
                }
                $f_where = array();
                $f_where['order_id'] = $value['order_id'];
                $f_where['refund_status'] = array('neq', '10');
                $list[$key]['ref_all'] = $g_order_goods_refund->where($f_where)->count();
            }

        }

        if (IS_AJAX) {
            echo json_encode($list);
            die;
        }

        $this->list = $list;
        $where = array();
        $where['user_del'] = 0;
        $where['user_id'] = $this->uid;
        $this->count = $order_model->where($where)->count();
        $where = array();
        $where['user_del'] = 0;
        $where['user_id'] = $this->uid;
        $where['pay_status'] = '0';//代付款
        $this->count00 = $order_model->where($where)->count();
        $where = array();
        $where['user_del'] = 0;
        $where['user_id'] = $this->uid;
        $where['pay_status'] = '2';//待发货
        $where['shipping_status'] = array('in', '0,3');
        $where['order_status'] = array('in', '1,0');//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
        $this->count10 = $order_model->where($where)->count();
        $where = array();
        $where['user_del'] = 0;
        $where['user_id'] = $this->uid;
        $where['pay_status'] = 2;// 支付状态；0，未付款；1，付款中 ；2，已付款
        $where['shipping_status'] = 1;//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
        $where['order_status'] = 1;//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
        $this->count20 = $order_model->where($where)->count();
        $where = array();
        $where['user_del'] = 0;
        $where['user_id'] = $this->uid;
        $where['pay_status'] = '2';//已完成
        //$where['shipping_status'] = '2';
        $where['_string'] = "shipping_status=2 or (shipping_status=1 and order_status in ('2','3','4'))";//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
        $this->count30 = $order_model->where($where)->count();
        $this->webtitle = "wqp米有项目框架";
        $this->display();

    }

    //订单信息
    public function order_detail()
    {
        
        $memberinfo_de = $this->getMemberDetail();
        $memberinfo_de['balance'] += $memberinfo_de['balance_give'];
        $this->MemberDetail = $memberinfo_de;
        $balance = $memberinfo_de['balance'];
        $balance = sprintf("%.2f", substr(sprintf("%.3f", $balance), 0, -2));
        $this->balance = $balance;
        $menuwhere["order_id"] = array("eq", $_GET["id"]);
        $menuwhere['user_id'] = $this->uid;
        $data = M("g_order_info")->where($menuwhere)->find();

        if ($data) {
            if($data['pay_name']=='alipay'){
                $data['payment']='支付宝支付';
            }else{
                $data['payment']='微信支付';
            }
            $order_goods = M('g_order_goods')->where(array('order_id' => $data["order_id"]))->select();
            if ($order_goods) {
                foreach ($order_goods as $key => $value) {
                    if ($value['is_refund']) {
                        $f_where = array();
                        $f_where['order_goods_id'] = $value['rec_id'];
                        $refund = M('g_order_goods_refund')->where($f_where)->find();
                        if ($refund) {
                            $refund = $this->get_refund_status($refund);
                            $order_goods[$key]['code_name'] = $refund['code_name'];
                        } else {
                            $order_goods[$key]['code_name'] = "退货";
                        }
                    }
                }
            }
            $offline_money = 0;

            if ($order_goods) {
                foreach ($order_goods as $key => $value) {
                    if ($value['offline']) {
                        $offline_money = $offline_money + $value['goods_number'] * $value['goods_price'];
                    }
                }
            }

            $this->order_goods = $order_goods;
            $order_show = $this->get_order_status($data);
            if ($data['order_amount'] == $offline_money) {
                $offline_money = $offline_money + $data['shipping_fee'];
            }
            $data['order_amount'] = $data['order_amount'] + $data['shipping_fee'];
            $online_money = $data['order_amount'] - $data['surplus'] - $offline_money;
            $this->online_money = $online_money;
            if ($online_money < 0) {///已经支付过了 不能货到付款
                $offline_money = 0;
            }
            $this->offline_money = $offline_money;

            $this->order_goods = $order_goods;
            $order_show = $this->get_order_status($data);
            $data['order_state'] = $order_show['code'];
            $data['order_state_name'] = $order_show['name'];
            if ($data['order_state'] == "delivered") {
                $f_where = array();
                $f_where['order_id'] = $data['order_id'];
                $f_where['refund_status'] = array('neq', '10');
                $this->ref_all = M('g_order_goods_refund')->where($f_where)->count();
            }
            $data = $this->get_order_msg_data($data);////订单显示信息
        }

        // 支付状态；0，未付款；1，付款中 ；2，已付款
		$pay_status = array('0' => '未付款', '1' => '已支付', '2' => '已付款', '100'=>'等待买家付款', '101'=>'已支付，对账中', '102'=>'支付已完成');
        $this->pay_status = $pay_status;
        //商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
        $shipping_status = array('0' => '未发货', '1' => '已发货', '2' => '已完成', '3' => '备货中');
        $this->shipping_status = $shipping_status;
        //订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
        $this->order_status = array('0' => '未确认', '1' => '已确认', '2' => '已取消', '3' => '无效', '4' => '退货');
//
        $title = "订单信息";
        $this->assign("data", $data);
        $this->display();
    }

    //订单支付信息
    public function order_pay() 
    {
        $memberinfo_de = $this->getMemberDetail();
        $memberinfo_de['balance'] += $memberinfo_de['balance_give'];
        $this->MemberDetail = $memberinfo_de;
        $balance = $memberinfo_de['balance'];
        $balance = sprintf("%.2f", substr(sprintf("%.3f", $balance), 0, -2));
        $this->balance = $balance;//账户余额

        $menuwhere["order_sn"] = array("eq", $_GET["pay_sn"]);
        $menuwhere['user_id'] = $this->uid;
        $data = M("g_order_info")->where($menuwhere)->find();
        // var_dump($data);
        // exit;
        if ($data) {
            if($data['pay_name']=='alipay'){
                $data['payment']='支付宝支付';
            }else{
                $data['payment']='微信支付';
            }
            $order_goods = M('g_order_goods')->where(array('order_id' => $data["order_id"]))->select();
            $offline_money = 0;
            if ($order_goods) {
                foreach ($order_goods as $key => $value) {
                    if ($value['offline']) {
                        $offline_money = $offline_money + $value['goods_number'] * $value['goods_price'];
                    }
                }
            }
            $this->order_goods = $order_goods;
            $order_show = $this->get_order_status($data);
            if ($data['order_amount'] == $offline_money) {
                $offline_money = $offline_money + $data['shipping_fee'];
            }
            $data['order_amount'] = $data['order_amount'] + $data['shipping_fee'];

            $online_money = $data['order_amount'] - $data['surplus'] - $offline_money;
            $this->online_money = $online_money;
            if ($online_money < 0) {///已经支付过了 不能货到付款
                $offline_money = 0;
            }
            $this->offline_money = $offline_money;

            $data['order_state'] = $order_show['code'];
            $data['order_state_name'] = $order_show['name'];
            if ($data['order_state'] == "delivered") {
                $f_where = array();
                $f_where['order_id'] = $data['order_id'];
                $f_where['refund_status'] = array('neq', '10');
                $this->ref_all = M('g_order_goods_refund')->where($f_where)->count();
            }
            $data = $this->get_order_msg_data($data);////订单显示信息

        }
        // 支付状态；0，未付款；1，付款中 ；2，已付款
        $pay_status = array('0' => '未付款', '1' => '已支付', '2' => '已付款', '100'=>'等待买家付款', '101'=>'已支付，对账中', '102'=>'支付已完成');
        $this->pay_status = $pay_status;
        //商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
        $shipping_status = array('0' => '未发货', '1' => '已发货', '2' => '已完成', '3' => '备货中');
        $this->shipping_status = $shipping_status;
        //订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
        $this->order_status = array('0' => '未确认', '1' => '已确认', '2' => '已取消', '3' => '无效', '4' => '退货');

        $title = "订单信息";
        $this->assign("data", $data);
        $this->display();
    }

    //订单显示信息
    public function get_order_msg_data($data = array())
    {
        if (empty($data)) {
            return $data;
        }
        switch ($data['discount_type']) {
            case '1':
                $data['discount_name'] = '抽奖';
                break;

            default:
                # code...
                break;
        }
        $time = time();
        $data['order_amount_all'] = $data['order_amount'];
        $data['discount_price'] = $data['discount'];
        if ($data['pay_status'] == 2) {
            $data['order_amount'] = PriceFormat(floatval($data['order_amount']) - floatval($data['discount']));
        } else {
            if ($data['discount_start_time'] <= $time && $data['discount_end_time'] >= $time) {
                $data['order_amount'] = PriceFormat(floatval($data['order_amount']) - floatval($data['discount']));
            } else {
                $data['discount_price'] = 0;
            }
        }

        return $data;
    }

    ///服务 订单提交
    public function set_order()
    {
        $return_data['status'] = 0;
        $cart_id = $_REQUEST['cart_id'];
        $address_id = $_REQUEST['address_id'];
        $discount = $_REQUEST['discount'];
        $uid = $_SESSION['member']['uid'];
        if (empty($_SESSION['member']['mobile'])) {
            //未绑定  手机
            $return_data['status'] = 2;
            $return_data['error'] = '请完善资料';
            echo json_encode($return_data);
            die;
        }
        //购买开关
        $buy_switch = M('sys_param')->where(array('param_code' => 'buy_switch'))->getField('param_value');
        if (empty($buy_switch)) {
            $return_data['error'] = '管理员已关闭交易';
            echo json_encode($return_data);
            die;
        }

        if (empty($address_id)) {
            $return_data['error'] = '请选择收货地址';
            echo json_encode($return_data);
            die;
        }
        $address = M('g_user_address')->where(array('address_id' => $address_id, 'user_id' => $uid))->find();
        if (empty($address)) {
            $return_data['error'] = '收货地址不存在';
            echo json_encode($return_data);
            die;
        }
        $cart_model = D('Cart');
        if ($discount) {
            $discount_msg = $cart_model->get_member_discount_one($discount, $uid);
            if (empty($discount_msg)) {
                $return_data['error'] = '该折扣已过期';
                echo json_encode($return_data);
                die;
            }
        }

        //$where['session_id']=session('session_id');
        $where['user_id'] = $uid;
        $where['rec_id'] = array('in', $cart_id);
        $list = $cart_model->getCartAll($where);
		
        //计算价格
        $list = $cart_model->getCartSettlement($list);
        if (empty($list['status'])) {
            $return_data['error'] = $list['error'];
            echo json_encode($return_data);
            die;
        }
        $goods = $list['goods_list'];
        $member = $this->getMemberInfo();

        $time = time();
        $pay_sn = makePaySn($uid);
        $order_data['order_sn'] = $pay_sn;
        $order_data['store_id'] = $shop['shop_id'];
        $order_data['store_name'] = $shop['shop_name'];
        $order_data['user_id'] = $uid;

        $order_data['consignee'] = $address['consignee'];
        $order_data['province'] = $address['province'];
        $order_data['city'] = $address['city'];//
        $order_data['district'] = $address['area'];//
        $order_data['address'] = $address['address_name'] . $address['address'];//用户消费时的折扣
        $order_data['zipcode'] = $address['zipcode'];//用户消费时的返利折扣
        $order_data['tel'] = $address['tel'];//
        $order_data['mobile'] = $address['mobile'];//
        $order_data['email'] = $address['email'];//
        $order_data['best_time'] = $address['best_time'];//收货人的最佳送货时间
        $order_data['sign_building'] = $address['sign_building'];//收货人的地址的标志性建筑

        $order_data['is_gift'] = $list['is_gift'];//活动类型0 无 1 限时抢购

        $order_data['goods_amount'] = $list['tolal'];//商品总金额
        $order_data['order_amount'] = $list['need_pay'];//应付款金额

        //记录折扣信息
        if ($discount_msg && $discount_msg['discount'] > 0 && $discount_msg['discount'] < 1) {
            $order_data['discount_type'] = $discount_msg['type'];//折扣类型 1 抽奖
            $order_data['discount'] = $list['need_pay'] - $list['need_pay'] * $discount_msg['discount'];//discount 折扣金额
            $order_data['discount_val'] = $discount_msg['discount'];//折扣
            $order_data['discount_start_time'] = $discount_msg['start_time'];
            $order_data['discount_end_time'] = $discount_msg['end_time'];
        }
/*        if ($list['need_pay'] < 68) {
            $order_data['shipping_fee'] = 10;//订单金额小于 68 须支付运费10元
        }*/
        $order_data['add_time'] = $time;

        $order_pay_data['buyer_id'] = $uid;
        $order_pay_data['pay_sn'] = $pay_sn;


        $order_model = M('g_order_info');
        $order_goods_model = M('g_order_goods');
        $order_pay_model = M('g_order_pay');

        $order_model->startTrans();//开起事务
        $order_goods_model->startTrans();//开起事务
        $order_pay_model->startTrans();//开起事务

        $add_order = $order_model->add($order_data);
        if ($add_order === false) {
            $return_data['error'] = "订单生成失败，请稍后再试.";
            $order_model->rollback();//回滚事务
            $order_goods_model->rollback();//回滚事务
            $order_pay_model->rollback();//回滚事务
            echo json_encode($return_data);
            die;
        }

        $add_order_pay = $order_pay_model->add($order_pay_data);
        $good_list = $goods;
        foreach ($good_list as $key => $value) {
            if ($value['rec_type'] == 1) {
                $value['goods_name'] = '【限时抢购】' . $value['goods_name'];
            }else{
                $value['goods_name'] =  $value['use_vip'] . $value['goods_name'];
            }
            $order_good_data['order_id'] = $add_order;
            $order_good_data['goods_id'] = $value['goods_id'];
            $order_good_data['goods_name'] = $value['goods_name'];//商品名
            $order_good_data['goods_sn'] = $value['goods_sn'];//商品的唯一货号
            $order_good_data['goods_price'] = $value['goods_price'];//商品价格
            $order_good_data['market_price'] = $value['market_price'];//商品价格
            $order_good_data['goods_number'] = $value['goods_number'];//商品数量
            $order_good_data['goods_image'] = $value['goods_img'];//
            $order_good_data['goods_attr_id'] = $value['goods_attr_id'];//商品实际成交价
            $order_good_data['goods_attr'] = $value['goods_attr'];//商家id
            $order_good_data['share_card'] = $value['share_card'];//分享者 card
            $order_good_data['share_money'] = $value['share_money'];//分享返利金额
            $order_good_data['is_refund'] = $value['is_refund'];//是否可退货 1是 0否
            $order_good_data['goods_shipping'] = $value['goods_shipping'];//包邮方式 默认SF顺风包邮
            $order_good_data['shipping_code'] = $value['shipping_code'];//包邮方式code
            $order_good_data['offline'] = $value['offline'];//货到付款
            $order_good_data['is_exchange'] = $value['is_exchange'];////是否可退货 1是 0否
            $order_good_data['is_gift'] = $value['rec_type'];//活动类型0 无 1 限时抢购
            $order_good_data['promote_start_date'] = $value['promote_start_date'];
            $order_good_data['promote_end_date'] = $value['promote_end_date'];
            $add_order_goods[] = $order_goods_model->add($order_good_data);

        }
        $add_order_goods = array_unique($add_order_goods);//去重
        //in_array如果设置该参数为 true，则检查搜索的数据与数组的值的类型是否相同。
        if ($add_order !== false && $add_order_pay !== false && in_array(false, $add_order_goods, true) === false) {
            $return_data['status'] = 1;
            $order_model->commit();//提交事务
            $order_goods_model->commit();//提交事务
            $order_pay_model->commit();//提交事务
            //记录订单日志
            $data = array();
            $data['order_id'] = $add_order;
            $data['order_amount'] = $list['need_pay'];
            M('g_pay_log')->add($data);
            //记录订单日志
            $data = array();
            $data['order_id'] = $add_order;
            $data['log_role'] = 'buyer';
            $data['log_msg'] = '用户下单成功';
            $data['log_orderstate'] = '10';
            $insert = D('Mallorder')->addOrderLog($data);

            $return_data['pay_sn'] = $pay_sn;
            //删除购物车
            // $del_where['session_id']=session('session_id');
            $del_where = array();
            $del_where['user_id'] = $uid;
            $del_where['rec_id'] = array('in', $cart_id);
            M('g_cart')->where($del_where)->delete();
        } else {
            $order_model->rollback();//回滚事务
            $order_goods_model->rollback();//回滚事务
            $order_pay_model->rollback();//回滚事务
            $return_data['error'] = "订单生成失败，请稍后再试.";
        }
        echo json_encode($return_data);
        die;
    }


    //确认收货
    public function order_delivered()
    {
        $return_data['status'] = 0;
        $o_where["order_id"] = array("eq", $_POST["order_id"]);
        $o_where['user_id'] = $this->uid;
        $data_info = M("g_order_info")->where($o_where)->find();
        if (empty($data_info)) {
            $return_data['error'] = "该订单不存在";
            echo json_encode($return_data);
            die;
        }
        $order_show = $this->get_order_status($data_info);
        if ($order_show['code'] != 'delivered') {//已发货
            $return_data['error'] = "订单状态错误";
            echo json_encode($return_data);
            die;
        }
        $refund = M('g_order_goods_refund')->where(array('member_id' => $data_info['user_id'], 'order_id' => $data_info['order_id']))->find();
        if (!empty($refund) && $refund['refund_status'] != '10') {//
            $return_data['error'] = "订单已退货不能确认";
            echo json_encode($return_data);
            die;
        }
        $model_order = D('Mallorder');
        //查询商家信息
        $model_order->startTrans();
        //更改订单状态
        $data = array();
        $data['shipping_status'] = 2;
        $data['finnshed_time'] = time();
        $order_res = $model_order->editOrder($data, $o_where);

        //记录商家日志
        if ($order_res !== false) {
            //记录订单日志
            $data = array();
            $data['order_id'] = $data_info['order_id'];
            $data['log_role'] = 'buyer';
            $data['log_msg'] = '订单确认收货';
            $data['log_orderstate'] = '40';
            $insert = $model_order->addOrderLog($data);
            
            ///用户返利 返积分 认证等
            $this->set_member_exchange($data_info);///用户 返利等操作
            $model_order->commit();
            $return_data['error'] = "操作成功";
            $return_data['status'] = 1;
            echo json_encode($return_data);
            die;
        } else {
            $model_order->rollback();
            $return_data['error'] = "操作失败";
            echo json_encode($return_data);
            die;
        }
    }

    ///用户返利 返积分 认证等   update hkj 取消 消费大于 188  认证
    ///uodate hkj 如果商品设置佣金  123 级返利不设置
    public function set_member_exchange($data_info = array())
    {
        if (empty($data_info)) {
            return false;
        }
        $pre = C('DB_PREFIX');//表前缀
        //用户自己返利  用户积分增加  返利日志 积分增加日志
        $field = 'mem.member_card,mem.recommend_code,mem.indirect_recommend_code,mem.indirect2_recommend_code'
            . ',mem.member_status,mem.member_vip_type,mem.member_vip_order'
            . ',md.provinceid,md.cityid,md.areaid';
        $member_info = M()->table($pre . 'member mem')->
        join($pre . 'member_detail md on mem.id=md.member_id')//
        ->where(array('mem.id' => $data_info['user_id']))//
        ->field($field)->find();
        //shop_rebate_status  123 级返利状态 1 返利  0不返
        $shop_rebate_status = 0;//返利类型 1分享返利 0正常返利(123级返利) 2升级返利
        $member_tuijian_data = array();//返利记录

        $order_save_data = array();//订单返利 数据
        $order_save_data['profit_type'] = 0;//返利类型 1分享返利 0正常返利(123级返利)
        $order_save_data['order_profit'] = $data_info['order_amount'];//订单利润= 应付款金额-订单返利
        $order_save_data['order_rebate'] = 0;//订单返利金额


        //直接推荐人
        if ($member_info['recommend_code']) {
            $member_info_1 = M('member')->where(array('member_card' => $member_info['recommend_code']))//
            ->field('id,member_card,member_status,mobile,member_vip_type')->find();
        }
        //间接推荐人
        if ($member_info['indirect_recommend_code']) {
            $member_info_2 = M('member')->where(array('member_card' => $member_info['indirect_recommend_code']))//
            ->field('id,member_card,member_status,mobile,member_vip_type')->find();
        }
        //间接二级推荐人
        if ($member_info['indirect2_recommend_code']) {
            $member_info_3 = M('member')->where(array('member_card' => $member_info['indirect2_recommend_code']))//
            ->field('id,member_card,member_status,mobile,member_vip_type')->find();
        }

        //推荐人中最近的旗舰店
        $flageship_info=getflageship($member_info['recommend_code']);
        $flage_level_info=M('member_level')->where('levelId=3')->find();//旗舰店的基本素养

        if ($data_info['is_upgrade']==1 ) {

            $shop_rebate_status = 2;
            $level_order_info=M('member_level_order')->where('id='.$data_info['order_sn'])->find();//升級訂單信息
            $upgrade_info=M('member_level')->where('levelId='.$level_order_info['levelId'])->find();//等級信息
            $member_vip_order = M('member')->where(array('id' => $data_info['user_id']))->save(array('member_vip_order' => $level_order_info['levelId'],'member_vip_type'=>$level_order_info['levelId']));//
            if (!empty($member_info_1) && !empty($member_info_1['member_vip_type']) && $member_vip_order !== false) {
                //$direct_auth_rebate = M('sys_param')->where(array('param_code' => 'direct_auth_rebate'))->getField('param_value');//返利比例；
                //返利金额
                if ($level_order_info['levelId']==1 &&$level_order_info['last_level']==0){//0升級到1，
                    $direct_auth_rebate=$upgrade_info['award_standard'];
                }elseif ($level_order_info['levelId']==2 &&$level_order_info['last_level']==1){//1升級到2，
                    $direct_auth_rebate=$upgrade_info['award_senior']-$upgrade_info['award_standard'];
                }elseif ($level_order_info['levelId']==2 &&$level_order_info['last_level']==0){//1升級到2，
                    $direct_auth_rebate=$upgrade_info['award_senior'];
                }

                //direct_auth_rebate返利金额
                if ($direct_auth_rebate > 0) {
                    $order_save_data['order_rebate'] += $direct_auth_rebate;//订单返利金额
                    $log = array();
                    $log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
                    $log['type5_type']=1;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
                    $log['order_id'] = $data_info['order_id'];
                    $log['des'] = '推荐人('.$member_info['member_card'].')升级VIP收益￥' . $direct_auth_rebate;
                    //加减用户 记录日志
                    $this->set_member_balance($member_info_1['id'], 1, $direct_auth_rebate, $log);
                    //加减vip 积分
                    $log = array();
                    $log['type'] = 1;////1 推荐vip升级 2 订单消费
                    $log['order_id'] = $data_info['order_id'];
                    $log['des'] = '推荐人('.$member_info['member_card'].')升级VIP';
                    $this->set_member_vip_integral($member_info_1['id'], 1, $direct_auth_rebate, $log);
                    //返利记录
                    $tuijian_data = array();
                    $tuijian_data['member_id'] = $member_info_1['id'];
                    $tuijian_data['order_id'] = $data_info['order_id'];
                    $tuijian_data['type'] = 4;
                    $tuijian_data['money'] = $direct_auth_rebate;
                    $tuijian_data['des'] = '推荐人('.$member_info['member_card'].')升级VIP收益：￥' . $direct_auth_rebate;
                    $member_tuijian_data[] = $tuijian_data;
                }

                $log=array();
                 $log['order_id']=$data_info['order_id'];
                 $log['des']='推荐人认证增加：10';
                 //加减用户积分 记录日志 直接推荐人+10积分[认证赠送]
                 $this->set_member_points($member_info_1['id'],1,10,$log);
            }

            //旗舰店以外的间接推荐人目前没有返利
            //旗舰店收益
            if (!empty($flageship_info)&&$flageship_info['id']!=$member_info_1['id']&&$level_order_info['last_level']==0){

                $add_child2=$flage_level_info['addChild2'];
                $order_save_data['order_rebate'] += $add_child2;
                $log = array();
                $log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
                $log['type5_type']=4;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
                $log['order_id'] = $data_info['order_id'];
                $log['des'] = '旗舰店('.$member_info['member_card'].')升级VIP收益￥' . $add_child2;
                //加减用户 记录日志
                $this->set_member_balance($flageship_info['id'], 1, $add_child2, $log);
                //返利记录
                $tuijian_data = array();
                $tuijian_data['member_id'] = $flageship_info['id'];
                $tuijian_data['order_id'] = $data_info['order_id'];
                $tuijian_data['type'] = 4;
                $tuijian_data['money'] = $add_child2;
                $tuijian_data['des'] = '旗舰店('.$member_info['member_card'].')升级VIP收益：￥' . $add_child2;
                $member_tuijian_data[] = $tuijian_data;
            }
        }


        //升级返利 end

        //-----------------------因为目前不要分享返利，所以注释掉----------------------------
/*            if (empty($shop_rebate_status)) {
            $order_goods = M('g_order_goods')->where(array('order_id' => $data_info["order_id"]))->select();
            $member_model = M('member');
            $goods_model = M("g_goods");
            if ($order_goods) {
                foreach ($order_goods as $key => $value) {
                    //增加销量
                    $goods_model->where(array("goods_id" => $value['goods_id']))->setInc("goods_salesvolume", $value['goods_number']);

                    if ($value['share_card'] && $value['share_money'] > 0) {
                        $member_share = $member_model->where(array('member_card' => $value['share_card']))
                        ->field('id,member_status,mobile')->find();
                        //认证返利
                        // if (!empty($member_share) && !empty($member_share['member_status'])) {
                        if (!empty($member_share) && $member_share['mobile']) {///绑定手机
                            $shop_rebate_status = 1;//如果商品 分享返利了 123 级返利不执行
                            $order_save_data['profit_type'] = 1;
                            //$rebate_indirect=M('sys_param')->where(array('param_code'=>'rebate_indirect'))->getField('param_value');//返利比例；
                            //$discount_rebate*$rebate_indirect;//返利金额
                            $share_money = $value['share_money'] * $value['goods_number'];
                            $order_save_data['order_rebate'] += $share_money;//订单返利金额

                            $log = array();
                            $log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
                            $log['order_id'] = $value['order_id'];
                            $log['des'] = '分享商品收益：￥' . $share_money;
                            //加减用户 记录日志
                            $this->set_member_balance($member_share['id'], 1, $share_money, $log);
                            //返利记录
                            $tuijian_data = array();
                            $tuijian_data['member_id'] = $member_share['id'];
                            $tuijian_data['order_id'] = $value['order_id'];
                            $tuijian_data['type'] = 6;
                            $tuijian_data['money'] = $value['share_money'];
                            $tuijian_data['des'] = '分享商品收益：￥' . $share_money;
                            $member_tuijian_data[] = $tuijian_data;
                        }
                    }
                }
            }
        }*/
/*             if (empty($shop_rebate_status)) {///分享 返利
              $order_save_data['order_profit'] = $order_save_data['order_profit'] - $order_save_data['order_rebate'];
              M('g_order_info')->where(array('order_id' => $data_info['order_id']))->save($order_save_data);
          }*/
        //增加用户积分 1：1
        $integral = round($data_info['order_amount']);
        if ($integral > 0) {
            $log = array();
            $log['order_id'] = $data_info['order_id'];
            $log['des'] = '商城订单消费增加：' . $integral;
            //加减用户 记录日志
            $this->set_member_points($data_info['user_id'], 1, $integral, $log);
        }
        //  $shop_rebate_status = 0;//返利类型 1分享返利 0正常返利(123级返利) 2升级返利
/*        if($member_info['member_vip_type']>0 || $shop_rebate_status==2){// 如果自己是会员 或者是升级返利
            //加减vip 积分
            $log = array();
            $log['type'] = 2;////1 推荐vip升级 2 订单消费
            $log['order_id'] = $data_info['order_id'];
            $log['money'] = $data_info['order_amount'];
            $log['des'] = '订单累计消费';
            $this->set_member_vip_integral($data_info['user_id'], 1, $data_info['order_amount'], $log);
        }*/

        ///商城返利比例
        //$shop_rebate = M('sys_param')->where(array('param_code' => 'shop_rebate'))->getField('param_value');//返利比例；
        //总返利金额
        //$discount_rebate = $data_info['order_amount'] * $shop_rebate;//返利金额
        $discount_rebate=0;
        $order_good_info=M('g_order_goods')->where('order_id='.$data_info['order_id'])->select();
        foreach ($order_good_info as $k=>$v){
            $goods_id=$v['goods_id'];
            $goods_number=$v['goods_number'];
            $goods_price=$v['goods_price'];
            $purchase_price=M('g_goods')->where("goods_id=$goods_id")->getField('purchase_price');
            $discount_rebate+=(($goods_price-$purchase_price)*$goods_number);
        }
        $order_profit_all=0;
        //123 返利
        if ($shop_rebate_status == 0 && $discount_rebate > 0 && $discount_rebate < $data_info['order_amount']) {
           $order_profit_all=$discount_rebate;
            //消费者本身返利比例
            //$rebate_consumer = M('sys_param')->where(array('param_code' => 'rebate_consumer'))->getField('param_value');//返利比例；
            ///用户自己返利
           // $discount_rebate_my = $discount_rebate * $rebate_consumer;//返利金额
/*                        if ($discount_rebate_my > 0) {

                            $order_save_data['order_rebate'] += $discount_rebate_my;//订单返利金额

                            $log = array();
                            $log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
                            $log['order_id'] = $data_info['order_id'];
                            $log['des'] = '订单' . $data_info['order_sn'] . '收益：￥' . $discount_rebate_my;
                            //加减用户 记录日志
                            $this->set_member_balance($data_info['user_id'], 1, $discount_rebate_my, $log);
                            //返利记录
                            $tuijian_data = array();
                            $tuijian_data['member_id'] = $data_info['user_id'];
                            $tuijian_data['order_id'] = $data_info['order_id'];
                            $tuijian_data['type'] = 1;
                            $tuijian_data['money'] = $discount_rebate_my;
                            $tuijian_data['des'] = '订单' . $data_info['order_sn'] . '收益：￥' . $discount_rebate_my;
                            $member_tuijian_data[] = $tuijian_data;
                        }*/
            ///用户自己返利end

            //直接推荐人返利
            //推荐人是 认证的才返利  是vip才返利
            // if (!empty($member_info_1) && !empty($member_info_1['member_status'])) {
            if (!empty($member_info_1) && $member_info_1['mobile'] && !empty($member_info_1['member_vip_type'])) {///绑定手机
                //$rebate_direct = M('sys_param')->where(array('param_code' => 'rebate_direct'))->getField('param_value');//返利比例；
                //$discount_rebate_1 = $discount_rebate * $rebate_direct;//返利金额
                $level_info_1=M('member_level')->where('levelId='.$member_info_1['member_vip_type'])->find();
                 $discount_rebate_1=$discount_rebate* ($level_info_1['sale_self']/100);
                if ($discount_rebate_1 > 0) {

                    $order_save_data['order_rebate'] += $discount_rebate_1;//订单返利金额

                    $log = array();
                    $log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
                    $log['type5_type']=1;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
                    $log['order_id'] = $data_info['order_id'];
                    $log['des'] = '直接推荐人('.$member_info['member_card'].')消费收益：￥' . $discount_rebate_1;
                    //加减用户 记录日志
                    $this->set_member_balance($member_info_1['id'], 1, $discount_rebate_1, $log);
                    //返利记录
                    $tuijian_data = array();
                    $tuijian_data['member_id'] = $member_info_1['id'];
                    $tuijian_data['order_id'] = $data_info['order_id'];
                    $tuijian_data['type'] = 2;
                    $tuijian_data['money'] = $discount_rebate_1;
                    $tuijian_data['des'] = '直接推荐人('.$member_info['member_card'].')消费收益：￥' . $discount_rebate_1;
                    $member_tuijian_data[] = $tuijian_data;
                }
            }
            //直接推荐人返利end

            //间接人返利
            //推荐人是 认证的才返利  是vip才返利
            // if (!empty($member_info_2) && !empty($member_info_2['member_status'])) {
            if (!empty($member_info_2) && $member_info_2['mobile'] && !empty($member_info_2['member_vip_type'])) {///绑定手机
                // $rebate_indirect = M('sys_param')->where(array('param_code' => 'rebate_indirect'))->getField('param_value');//返利比例；
                //$discount_rebate_2 = $discount_rebate * $rebate_indirect;//返利金额
                $level_info_2=M('member_level')->where('levelId='.$member_info_2['member_vip_type'])->find();
                $discount_rebate_2=$discount_rebate * ($level_info_2['sale_child']/100);
                if ($discount_rebate_2) {

                    $order_save_data['order_rebate'] += $discount_rebate_2;//订单返利金额

                    $log = array();
                    $log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
                    $log['type5_type']=3;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
                    $log['order_id'] = $data_info['order_id'];
                    $log['des'] = '间接推荐人('.$member_info['member_card'].')消费收益：￥' . $discount_rebate_2;
                    //加减用户 记录日志
                    $this->set_member_balance($member_info_2['id'], 1, $discount_rebate_2, $log);
                    //返利记录
                    $tuijian_data = array();
                    $tuijian_data['member_id'] = $member_info_2['id'];
                    $tuijian_data['order_id'] = $data_info['order_id'];
                    $tuijian_data['type'] = 3;
                    $tuijian_data['money'] = $discount_rebate_2;
                    $tuijian_data['des'] = '间接推荐人('.$member_info['member_card'].')消费收益：￥' . $discount_rebate_2;
                    $member_tuijian_data[] = $tuijian_data;
                }
            }
            //三级推荐人返利---目前只有旗舰店返利
            if (!empty($member_info_3) && $member_info_3['mobile'] && !empty($member_info_3['member_vip_type'])) {///绑定手机
                // $rebate_indirect = M('sys_param')->where(array('param_code' => 'rebate_indirect'))->getField('param_value');//返利比例；
                //$discount_rebate_2 = $discount_rebate * $rebate_indirect;//返利金额
                $level_info_3=M('member_level')->where('levelId='.$member_info_3['member_vip_type'])->find();
                $discount_rebate_3=$discount_rebate * ($level_info_3['sale_child2']/100);
                if ($discount_rebate_3) {

                    $order_save_data['order_rebate'] += $discount_rebate_3;//订单返利金额

                    $log = array();
                    $log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
                    $log['type5_type']=4;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
                    $log['order_id'] = $data_info['order_id'];
                    $log['des'] = '间接推荐人('.$member_info['member_card'].')消费收益：￥' . $discount_rebate_3;
                    //加减用户 记录日志
                    $this->set_member_balance($member_info_3['id'], 1, $discount_rebate_3, $log);
                    //返利记录
                    $tuijian_data = array();
                    $tuijian_data['member_id'] = $member_info_3['id'];
                    $tuijian_data['order_id'] = $data_info['order_id'];
                    $tuijian_data['type'] = 3;
                    $tuijian_data['money'] = $discount_rebate_3;
                    $tuijian_data['des'] = '间接推荐人('.$member_info['member_card'].')消费收益：￥' . $discount_rebate_3;
                    $member_tuijian_data[] = $tuijian_data;
                }
            }
            //间接二级返利--------暂时没有
            //推荐人是 认证的才返利  是vip才返利

            // if (!empty($member_info_3) && !empty($member_info_3['member_status'])) {
/*            if (!empty($member_info_3) && $member_info_3['mobile'] && !empty($member_info_3['member_vip_type'])) {///绑定手机
                //$rebate_indirect_two = M('sys_param')->where(array('param_code' => 'rebate_indirect_two'))->getField('param_value');//返利比例；
                //$discount_rebate_3 = $discount_rebate * $rebate_indirect_two;//返利金额
                $level_info_3=M('member_level')->where('levelId='.$member_info_3['member_vip_type'])->find();
                $discount_rebate_3=$data_info['order_amount'] * ($level_info_['sale_self']/100)
                if ($discount_rebate_3 > 0) {

                    $order_save_data['order_rebate'] += $discount_rebate_3;//订单返利金额

                    $log = array();
                    $log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
                    $log['type5_type']=3;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
                    $log['order_id'] = $data_info['order_id'];
                    $log['des'] = '间接二级推荐人('.$member_info['member_card'].')消费收益：￥' . $discount_rebate_3;
                    //加减用户 记录日志
                    $this->set_member_balance($member_info_3['id'], 1, $discount_rebate_3, $log);
                    //返利记录
                    $tuijian_data = array();
                    $tuijian_data['member_id'] = $member_info_3['id'];
                    $tuijian_data['order_id'] = $data_info['order_id'];
                    $tuijian_data['type'] = 5;
                    $tuijian_data['money'] = $discount_rebate_3;
                    $tuijian_data['des'] = '间接二级推荐人('.$member_info['member_card'].')消费收益：￥' . $discount_rebate_3;
                    $member_tuijian_data[] = $tuijian_data;
                }
            }*/
            //间接二级返利end

            //区域代理返利
            //区域代理是 认证的才返利  是vip才返利
            // if (!empty($member_info_3) && !empty($member_info_3['member_status'])) {
            /*            if (!empty($member_info_area)) {///
                            // $rebate_indirect_two = M('sys_param')->where(array('param_code' => 'rebate_indirect_two'))->getField('param_value');//返利比例；
                            $rebate_indirect_area= $member_info_area['rate'];
                            $discount_rebate_area = $discount_rebate * $rebate_indirect_area;//返利金额
                            if ($discount_rebate_area > 0) {

                                $order_save_data['order_rebate'] += $discount_rebate_area;//订单返利金额

                                $log = array();
                                $log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
                                $log['type5_type']=4;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
                                $log['order_id'] = $data_info['order_id'];
                                $log['des'] = '代理区域会员('.$member_info['member_card'].')消费收益：￥' . $discount_rebate_area;
                                //加减用户 记录日志
                                $this->set_member_balance($member_info_area['id'], 1, $discount_rebate_area, $log);
                                //返利记录
                                $tuijian_data = array();
                                $tuijian_data['member_id'] = $member_info_area['id'];
                                $tuijian_data['order_id'] = $data_info['order_id'];
                                $tuijian_data['type'] = 5;
                                $tuijian_data['money'] = $discount_rebate_area;
                                $tuijian_data['des'] = '代理区域会员('.$member_info['member_card'].')消费收益：￥' . $discount_rebate_area;
                                $member_tuijian_data[] = $tuijian_data;
                            }
                        }*/
            // //区域代理返利end

        }
        //订单返利类型
        $order_save_data['profit_type'] = $shop_rebate_status;
        $order_save_data['order_profit_all'] = $order_profit_all;
        //订单利润 order_profit
        //订单返利金额 order_rebate
        //订单返利总金额 返利池 order_profit_all
        $order_save_data['order_profit'] = $order_save_data['order_profit'] - $order_save_data['order_rebate'];
        M('g_order_info')->where(array('order_id' => $data_info['order_id']))->save($order_save_data);


        if (!empty($member_tuijian_data)) {//记录手游记录
            $rebate_record_model = M('rebate_record');
            $time = time();
            foreach ($member_tuijian_data as $key => $value) {
                $value['add_time'] = $time;
                $value['status'] = 1;//状态 1用户收益 2 商家返利
                $rebate_record_model->add($value);
            }
        }

    }


    //业绩   10-13修改只显示已完成的订单 gqh
    public function share()
    {
         /*
        $pre = C('DB_PREFIX');//表前缀
        $where['or_good.share_card'] = $this->member_card;
        $where['ord.order_status'] = 1;
        $where['ord.shipping_status'] = 2;
        //$where['is_attention']=1;
        $p = $_REQUEST['p'];
        $pagesize = 10;
        $p = !empty($p) ? $p : 1;
        $start = ($p - 1) * $pagesize;
        $field = "or_good.*,ord.order_status,ord.shipping_status,ord.pay_status";
        $list = M()->table($pre . 'g_order_goods or_good')//
        ->join($pre . 'g_order_info ord on ord.order_id=or_good.order_id')//
        ->where($where)//
        ->field($field)->limit($start, $pagesize)->order('or_good.rec_id desc')->select();
        foreach ($list as $key => $value) {
            $order_share_status = $this->get_order_share_status($value);
            $list[$key]['code'] = empty($value['share_money']) ? '0' : $value['share_money'];
            $list[$key]['code'] = $order_share_status['code'];
            $list[$key]['code_name'] = $order_share_status['name'];
        }
        if (IS_AJAX) {
            echo json_encode($list);
            die;
        }
        $this->list = $list;
        $count = M()->table($pre . 'g_order_goods or_good')//
        ->join($pre . 'g_order_info order on order.order_id=or_good.goods_id')//
        ->where($where)->count();
        //已支付 已完成
        //$where['or_good.share_card']=$this->member_card;
        $where['ord.pay_status'] = 2;// 支付状态；0，未付款；1，付款中 ；2，已付款
        $where['ord.order_status'] = array('in', '1,4');//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
        $where['ord.shipping_status'] = 2;//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
        $this->count_share = M()->table($pre . 'g_order_goods or_good')//
        ->join($pre . 'g_order_info ord on ord.order_id=or_good.order_id')//
        ->where($where)->count();
		*/
		 $where['member_id']=$this->uid;
         $p=$_REQUEST['p'];
         $pagesize=10;
         $p=!empty($p)?$p:1;
         $start=($p-1)*$pagesize;
         $type=$_REQUEST['type'];//1积分 0 米值
         $field="*";
         $model=M('member_consume_record');
         $arr=array('1'=>'订单消费','2'=>'充值','3'=>'提现','4'=>'退款','5'=>'收益','6'=>'认证消费','7'=>'系统赠送');
        $where['status']=1;
		$where['type']=5;
        $where['type5_type']=1;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
         $list=$model->where($where)//
        ->field($field)->limit($start,$pagesize)->order('add_time desc')->select();
        //消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
       
        if(!empty($list)){
             foreach ($list as $key => $value) {
               $typename=$arr[$value['type']];
               $typename?$typename:'-';
               $list[$key]['typename']=$typename;
               $list[$key]['status']=$value['status']==1?'+':'-';
               $list[$key]['add_time']=date("Y/m/d",$value['add_time']);
            }
        }
        if(IS_AJAX){
            echo json_encode($list);die;
        }
        $this->list=$list;
        $data['balance_all']=sprintf("%.0f",substr(sprintf("%.3f", $data['balance_all']), 0, -3));
        $count=$model->where($where)->sum('money');
        $count=sprintf("%.0f",substr(sprintf("%.3f", $count), 0, -3));
        $this->count_share = $count;
        $this->display();
    }

    //获取订单状态
    public function get_order_share_status($order_info = array())
    {
        if (empty($order_info)) {
            return array();
        }
// pay_status支付状态；0，未付款；1，付款中 ；2，已付款
// shipping_status 商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
//order_status订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
        $order_status = array('0' => '未确认', '1' => '已确认', '2' => '已取消', '3' => '无效', '4' => '退货');
        $shipping_status = array('0' => '未发货', '1' => '已发货', '2' => '已完成', '3' => '备货中');
        $code = $name = "";
        if ($order_info['order_status'] == 1) {//已确认
            $name = '进行中';
            switch ($order_info['shipping_status']) {
                case '1':
                    $code = "delivered";//已发货
                    break;
                case '2':
                    $code = "received";//已收货
                    $name = "已完成";
                    break;
                default:
                    $code = 'nondelivery';//未发货
                    break;
            }
            return array('code' => $code, 'name' => $name);
        } else {//未确认
            //2已取消；3无效；4，退货；
            if (in_array($order_info['order_status'], array('2', '3', '4'))) {
                if ($order_info['order_status'] == 4) {
                    return array('code' => '', 'name' => '已完成');
                } else {
                    return array('code' => '', 'name' => $order_status[$order_info['pay_status']]);
                }
            } else {////未确认
                if ($order_info['pay_status'] == 2) {//已付款 待确认
                    return array('code' => 'unconfirmed', 'name' => '进行中');
                } else {
                    return array('code' => 'nopay', 'name' => '未付款');
                }
            }
        }

    }

    ///支付
    public function go_pay()
    {
        $return_data['status'] = 0;
        $order_id = $_REQUEST['order_id'];
        $uid = $this->uid;
        $mem_password = $_REQUEST['mem_password'];
        $pay_type = $_REQUEST['pay_type'];
        $use_balance = $_REQUEST['use_balance'];
        //购买开关
        $buy_switch = M('sys_param')->where(array('param_code' => 'buy_switch'))->getField('param_value');
        if (empty($buy_switch)) {
            $return_data['error'] = '管理员已关闭交易';
            echo json_encode($return_data);
            die;
        }
        $model_order = D('Mallorder');
        if ($pay_type == "pay_online") {//在线支付
            $save_data = array();
            $save_data['offline'] = 0;//改变订单 货到付款状态
            $res = M('g_order_info')->where(array('order_id' => $order_id))->save($save_data);
            if ($res === false) {
                $return_data['error'] = '支付错误 请刷新页面重试';
                $return_data['status'] = 0;
                echo json_encode($return_data);
                die;
            }
            if ($use_balance) {//使用余额支付
                $this->balance_pay();
                die;
            } else {
                $condition = array();
                $condition['order_id'] = $order_id;
                $condition['pay_status'] = '0';// 支付状态；0，未付款；1，付款中 ；2，已付款
                $order_list = $model_order->getOrderList($condition, '', 'order_id,order_sn,order_amount,shipping_fee,surplus,surplus_give,discount_start_time,discount_end_time,discount');
                if (empty($order_list)) {
                    $return_data['error'] = "该订单不存在";
                    echo json_encode($return_data);
                    die;
                }
                ////未使用余额支付
                $_GET['return'] = 1;
                $_GET['pay_sn'] = $order_list[0]['order_sn'];
                //$get_pay_url = $this->get_pay_url();
                $return_data['need_pay'] = 1;///需要支付 1  不需要支付0
                $return_data['status'] = 1;
               /* if ($get_pay_url['status'] == 1) {
                    $return_data['status'] = 1;
                    $return_data['pay_url'] = $get_pay_url['pay_url'];
                } else {
                    $return_data['error'] = $get_pay_url['error'];
                    $return_data['status'] = 0;
                }*/
                echo json_encode($return_data);
                die;
            }
        } else {  //pay_offline货到付款


            //重新计算在线支付且处于待支付状态的订单总额
            $condition = array();
            $condition['order_id'] = $order_id;
            $condition['pay_status'] = '0';// 支付状态；0，未付款；1，付款中 ；2，已付款
            $order_list = $model_order->getOrderList($condition, '', 'order_id,order_sn,order_amount,shipping_fee,surplus,surplus_give,discount_start_time,discount_end_time,discount');
            if (empty($order_list)) {
                $return_data['error'] = "该订单不存在";
                echo json_encode($return_data);
                die;
            }
            //计算本次需要在线支付的订单总金额
            $time = time();
            $pay_amount = 0;
            $offline_money = 0;
            $fee_offline_money = 0;//加运费的货到付款总额
            foreach ($order_list as $order_info) {
                ///减去余额支付部分 减去折扣部分
                ///折扣是否过期
                $pay_amount += PriceFormat(floatval($order_info['shipping_fee']));//运费
                if ($order_info['discount_start_time'] <= $time && $order_info['discount_end_time'] >= $time) {
                    $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['surplus']) - floatval($order_info['discount']));
                } else {
                    $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['surplus']));
                }
                $order_goods = M('g_order_goods')->where(array('order_id' => $order_info["order_id"]))->select();
                if ($order_goods) {
                    foreach ($order_goods as $keys => $value) {
                        if ($value['offline']) {
                            if ($order_info['discount_start_time'] <= $time && $order_info['discount_end_time'] >= $time) {
                                $offline_money = PriceFormat(floatval($offline_money) + floatval($value['goods_number'] * $value['goods_price'] * $order_info['discount_val']));
                            } else {
                                $offline_money = PriceFormat(floatval($offline_money) + floatval($value['goods_number'] * $value['goods_price']));
                            }
                        }
                    }
                    $fee_offline_money += PriceFormat(floatval($offline_money) + floatval($order_info['shipping_fee']));
                }
            }

            //如果为空，说明已经都支付过了或已经取消或者是价格为0的商品订单，全部返回
            if (empty($pay_amount)) {
                $return_data['error'] = "订单金额为0，不需要支付";
                echo json_encode($return_data);
                die;
            }


            ///余额支付部分 大于 总的支付金额
            if ($fee_offline_money > $pay_amount) {
                $return_data['error'] = "余额支付错误,请选择在线支付";
                echo json_encode($return_data);
                die;
            } else if ($fee_offline_money == $pay_amount) {
                //全部活到付款
                $save_data = array();
                $save_data['offline'] = 1;
                $save_data['offline_money'] = $fee_offline_money;
                $save_data['pay_status'] = '2';
                $save_data['pay_time'] = time();
                $res = M('g_order_info')->where(array('order_id' => $order_id))->save($save_data);
                if ($res !== false) {
                    //记录订单日志
                    $data = array();
                    $data['order_id'] = $order_id;
                    $data['log_role'] = 'buyer';
                    $data['log_msg'] = '用户使用货到付款￥' . $offline_money;
                    $data['log_orderstate'] = '20';
                    $insert = D('Mallorder')->addOrderLog($data);

                    $return_data['need_pay'] = 0;///需要支付 1  不需要支付0
                    $return_data['status'] = 1;

                    echo json_encode($return_data);
                    die;
                } else {
                    $return_data['error'] = "支付错误 请刷新页面重试";
                    echo json_encode($return_data);
                    die;
                }

            } else if ($fee_offline_money < $pay_amount && $offline_money > 0) {
                ///部分货到付款  部分在线支付
                $save_data = array();
                $save_data['offline'] = 1;
                $save_data['offline_money'] = $offline_money;
                $res = M('g_order_info')->where(array('order_id' => $order_id))->save($save_data);
                if ($res === false) {
                    $return_data['error'] = '支付错误 请刷新页面重试';
                    $return_data['status'] = 0;
                    echo json_encode($return_data);
                    die;
                }
                if ($use_balance) {//使用余额支付
                    $this->balance_pay();
                    die;
                } else {
                    $_GET['return'] = 1;
                    $_GET['pay_sn'] = $order_list[0]['order_sn'];
                    $return_data['status'] = 1;
                    $return_data['need_pay'] = 1;///需要支付 1  不需要支付0
                    /*$get_pay_url = $this->get_pay_url();
                    $return_data['need_pay'] = 1;///需要支付 1  不需要支付0
                    if ($get_pay_url['status'] == 1) {
                        $return_data['status'] = 1;
                        $return_data['pay_url'] = $get_pay_url['pay_url'];
                    } else {
                        $return_data['error'] = $get_pay_url['error'];
                        $return_data['status'] = 0;
                    }*/
                    echo json_encode($return_data);
                    die;
                }
            } else {//支付错误 请刷新页面重试
                $return_data['error'] = '支付错误 请刷新页面重试';
                $return_data['status'] = 0;
                echo json_encode($return_data);
                die;
            }

        }
    }

    ///余额支付
    public function balance_pay()
    {
        $return_data['status'] = 0;
        $order_id = $_REQUEST['order_id'];
        $uid = $this->uid;
        $mem_password = $_REQUEST['mem_password'];
        $pay_type = $_REQUEST['pay_type'];

        if (empty($mem_password)) {
            $return_data['error'] = "密码不能为空";
            echo json_encode($return_data);
            die;
        }
        $member = $this->getMemberInfo();
        if ($member['password'] != md5($mem_password)) {
            $return_data['error'] = "密码错误";
            echo json_encode($return_data);
            die;
        }
        $memberinfo_de = $this->getMemberDetail();
        if (empty($memberinfo_de)) {
            $return_data['error'] = "用户不存在";
            echo json_encode($return_data);
            die;
        }
        $balance = $memberinfo_de['balance'] + $memberinfo_de['balance_give'];
        $balance = sprintf("%.2f", substr(sprintf("%.3f", $balance), 0, -2));
        if ($balance <= 0) {
            $return_data['error'] = "余额不足";
            echo json_encode($return_data);
            die;
        }
        $model_order = D('Mallorder');
        //重新计算在线支付且处于待支付状态的订单总额
        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['pay_status'] = '0';// 支付状态；0，未付款；1，付款中 ；2，已付款
        $order_list = $model_order->getOrderList($condition, '', 'order_id,order_sn,user_id,order_amount,shipping_fee,is_upgrade,surplus,surplus_give,discount_start_time,discount_end_time,discount,offline,offline_money');
        if (empty($order_list)) {
            $return_data['error'] = "该订单不存在";
            echo json_encode($return_data);
            die;
        }
        //计算本次需要在线支付的订单总金额
        $time = time();
        $pay_amount = 0;
        $offline_money = 0;
        $fee_offline_money = 0;//加运费的货到付款总额
        foreach ($order_list as $order_info) {
            $pay_amount += PriceFormat(floatval($order_info['shipping_fee']));//运费
            ///减去余额支付部分 减去折扣部分
            ///折扣是否过期
            if ($order_info['discount_start_time'] <= $time && $order_info['discount_end_time'] >= $time) {
                $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['surplus']) - floatval($order_info['discount']));
            } else {
                $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['surplus']));
            }
            if ($order_info['offline']) {
                $pay_amount -= $order_info['offline_money'];//
            }

        }

        //如果为空，说明已经都支付过了或已经取消或者是价格为0的商品订单，全部返回
        if (empty($pay_amount)) {
            $return_data['error'] = "订单金额为0，不需要支付";
            echo json_encode($return_data);
            die;
        }

        $consume_record_model = M('member_consume_record');
        $member_detail_model = M('member_detail');
        $model_order = M('g_order_info');

        $need_pay = 1;//还需要支付现金
        $m_s_data = array();
        $surplus_give = 0;///支付的赠送余额
        if ($pay_amount > $balance) {//订单金额大于余额  扣除所有余额

            $m_s_data['balance_give'] = 0;///扣除所有赠送余额
            //扣除余额 加上 赠送余额
            $m_s_data['balance'] = $memberinfo_de['balance'] - $balance + $memberinfo_de['balance_give'];//余额
            $surplus_give = $memberinfo_de['balance_give'];
            $money = $balance;
        } else {//订单金额小于等于 余额
            if ($pay_amount > $memberinfo_de['balance_give']) {
                //支付金额 大于 赠送余额 扣除全部赠送余额
                $m_s_data['balance_give'] = 0;
                $m_s_data['balance'] = $memberinfo_de['balance'] - $pay_amount + $memberinfo_de['balance_give'];
                $surplus_give = $memberinfo_de['balance_give'];
            } else {
                //支付金额 小于 等于赠送余额 扣除订单金额的赠送余额
                $m_s_data['balance_give'] = $memberinfo_de['balance_give'] - $pay_amount;
                $surplus_give = $pay_amount;
            }
            $need_pay = 0;//不需要支付现金
            $money = $pay_amount;
        }
        $time = time();
        $log = array();
        $log['status'] = 0;//支出
        $log['add_time'] = $time;
        $log['member_id'] = $uid;
        $log['money'] = $money;
        $log['type'] = 1;
        $log['des'] = '用户使用余额支付￥' . $money;
        $save_order = array();
        $save_order['surplus'] = $order_list[0]['surplus'] + $money;
        $save_order['surplus_give'] = $order_list[0]['surplus_give'] + $surplus_give;//支付的赠送余额
        if (empty($need_pay)) {
            $save_order['pay_status'] = '2';
            $save_order['pay_time'] = $time;
        }
        $member_detail_model->startTrans();//开起事务
        $consume_record_model->startTrans();//开起事务
        $model_order->startTrans();//开起事务
        $m_res = $member_detail_model->where(array('member_id' => $uid))->save($m_s_data);
        $c_res = $consume_record_model->add($log);
        $order_res = $model_order->where(array('order_id' => $order_id))->save($save_order);

        //in_array如果设置该参数为 true，则检查搜索的数据与数组的值的类型是否相同。
        if ($m_res !== false && $c_res !== false && $order_res !== false) {
            $return_data['status'] = 1;
            $return_data['need_pay'] = $need_pay;
            $log_msg = '用户使用余额支付￥' . $money;
            if ($need_pay) {//需要继续支付
                $_GET['return'] = 1;
                $_GET['pay_sn'] = $order_list[0]['order_sn'];
               /* $get_pay_url = $this->get_pay_url();
                if ($get_pay_url['status'] == 1) {
                    $return_data['pay_url'] = $get_pay_url['pay_url'];
                } else {
                    $return_data['error'] = $get_pay_url['error'];
                    $return_data['status'] = 0;
                }*/
            } else {//余额  支付完成
                //支付完成 发送短信通知
                $this->order_sendSMS($order_list[0]['order_sn'], $save_order['surplus'], '余额支付');
                //购买成功  查询是否是会员 不是会员则升级为会员
                if ($order_list[0]['is_upgrade']) {//升级订单
                    $member = M('member')->where(array('id' => $order_list[0]['user_id']))->field('id,member_vip_type')->find();
                    if ($member && empty($member['member_vip_type'])) {
                        $reee = M('member')->where(array('id' => $order_list[0]['user_id']))->save(array('member_vip_type' => 1,'vip_time'=>time()));
                        $log_msg .= '升级会员成功';
                    }
                }

            }

            $model_order->commit();//提交事务
            $consume_record_model->commit();//提交事务
            $member_detail_model->commit();//提交事务
            //记录订单日志
            /* if(empty($need_pay)){//订单支付日志
               $data = array();
               $data['order_id'] = $order_id;
               $data['order_amount'] =$money;
                M('g_pay_log')->add($data);
              }*/
            //记录订单日志
            $data = array();
            $data['order_id'] = $order_id;
            $data['log_role'] = 'buyer';
            $data['log_msg'] = $log_msg;
            if (empty($need_pay)) {
                $data['log_orderstate'] = '20';
            } else {
                $data['log_orderstate'] = '10';
            }
            $insert = D('Mallorder')->addOrderLog($data);
        } else {
            $model_order->rollback();//回滚事务
            $consume_record_model->rollback();//回滚事务
            $member_detail_model->rollback();//回滚事务
            $return_data['error'] = "支付失败请稍候再试.";
        }
        echo json_encode($return_data);
        die;
    }


    //订单删除
    public function order_del()
    {
        $return_data['status'] = 0;
        $o_where["order_id"] = array("eq", $_POST["order_id"]);
        $o_where['user_id'] = $this->uid;
        $o_where['user_del'] = 0;
        $data_info = M("g_order_info")->where($o_where)->find();
        if (empty($data_info)) {
            $return_data['error'] = "该订单不存在";
            echo json_encode($return_data);
            die;
        }
        $order_show = $this->get_order_status($data_info);
        if (!in_array($order_show['code'], array('received', 'nopay', 'finish'))) {//已发货
            $return_data['error'] = "订单状态错误";
            echo json_encode($return_data);
            die;
        }
        $order_res = M("g_order_info")->where($o_where)->save(array('user_del' => 1));
        //记录商家日志
        if ($order_res !== false) {
            if ($order_show['code'] == 'nopay' && $data_info['surplus'] > 0) {//未付款 已支付的订单退款 （余额支付）
                $log = array();
                $log['type'] = 4;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
                $log['order_id'] = $data_info['order_id'];
                $log['des'] = '取消订单退余额支付金额：￥' . $data_info['surplus'];
                //加减用户 记录日志  状态 1收入 2支出  如果有赠送余额支付 扣除赠送余额
                $return_data['user_b'] = $this->set_member_balance($data_info['user_id'], 1, $data_info['surplus'], $log, $data_info['surplus_give']);
                if ($return_data['user_b']) {
                    //记录订单日志
                    $data = array();
                    $data['order_id'] = $data_info['order_id'];
                    $data['log_role'] = 'buyer';
                    $data['log_msg'] = '取消订单退余额支付金额：￥' . $data_info['surplus'];
                    $data['log_orderstate'] = '0';
                    $insert = D('Mallorder')->addOrderLog($data);
                }

            } elseif ($order_show['code'] == 'nopay') {
                //记录订单日志
                $data = array();
                $data['order_id'] = $data_info['order_id'];
                $data['log_role'] = 'buyer';
                $data['log_msg'] = '取消订单';
                $data['log_orderstate'] = '0';
                $insert = D('Mallorder')->addOrderLog($data);
            }


            $return_data['code'] = $order_show['code'];
            $return_data['status'] = 1;
            echo json_encode($return_data);
            die;
        } else {
            $return_data['error'] = "操作失败";
            echo json_encode($return_data);
            die;
        }
    }

    ///支付
    public function go_wx_pay(){
        $return_data['status']=0;
        $order_sn=I('order_sn');
        $pay_type=I('pay_type');
        $pay_name = I('pay_name');
        //购买开关
        $buy_switch=M('sys_param')->where(array('param_code'=>'buy_switch'))->getField('param_value');
        if(empty($buy_switch)){
            $return_data['error']='管理员已关闭交易';
            echo json_encode($return_data);die;
        }
        $model_order = D('Mallorder');
        $save_data=array();
        $save_data['pay_name']=$pay_name;//改变订单 支付方式
        $res=M('g_order_info')->where(array('order_sn'=>$order_sn))->save($save_data);
        if($res===false){
            $return_data['error']='支付错误，请刷新页面重试';
            $return_data['status']=0;
            echo json_encode($return_data);die;
        }
        //在线支付
        $condition = array();
        $condition['order_sn'] = $order_sn;
        $condition['pay_status'] = '0';// 支付状态；0，未付款；1，付款中 ；2，已付款
        $order_list = $model_order->getOrderList($condition,'','*');
        if (empty($order_list)) {
            $return_data['error']="该订单不存在";
            echo json_encode($return_data);die;
        }
        //计算本次需要在线支付的订单总金额
        $time=time();
        $pay_amount = 0;
        $offline_money=0;
        foreach ($order_list as $order_info) {
            ///减去余额支付部分 减去折扣部分
            ///折扣是否过期
            if($order_info['discount_start_time']<=$time && $order_info['discount_end_time']>=$time){
                $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['first_discount'])  - floatval($order_info['surplus']) - floatval($order_info['discount']));
            }else{
                $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['first_discount']) - floatval($order_info['surplus']));
            }
        }
        //如果为空，说明已经都支付过了或已经取消或者是价格为0的商品订单，全部返回
        if (empty($pay_amount)) {
            $return_data['error']="订单金额为0，不需要支付";
            echo json_encode($return_data);die;
        }
        $pay_sn=$order_list[0]['order_sn'];
        $get_pay_url=$this->get_pay_url($pay_sn,$pay_amount);
        $return_data['need_pay']=1;///需要支付 1  不需要支付0
        if($get_pay_url['status']==1){
            $return_data['status']=1;
            $return_data['pay_url']=$get_pay_url['pay_url'];
        }else{
            $return_data['error']=$get_pay_url['error'];
            $return_data['status']=0;
        }
        echo json_encode($return_data);die;

    }
    ///获取支付链接
    public function get_pay_url($pay_sn = '', $pay_amount = 0)
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger') === false) {
            $data['status'] = 0;
            $data['error'] = '请在微信上打开支付';
            if ($return == 1) {
                return $data;
            }
            echo json_encode($data);
            die;
        }
        $payment_code = 'wxpay';
        if ($payment_code == "wxpay") {
            $user_open_id = $_SESSION['user_open_id'];
            if (empty($user_open_id)) {
                $data['status'] = 0;
                $data['error'] = "拉起支付失败，请刷新页面再试";
                session('user_open_error', null);
                if ($return == 1) {
                    return $data;
                }
                echo json_encode($data);
                die;
            }
            $url = 'pay_sn=' . $pay_sn
                . '&pay_amount=' . $pay_amount
                //    .'&subject='.$order_pay_info['subject']
                . '&openid=' . $user_open_id;

            $url = "http://" . $_SERVER['HTTP_HOST'] . '/api/payment/wpay/get_pay_fenxiao.php?' . $url;
            $data['status'] = 1;
            $data['pay_url'] = $url;
            return $data;
        }

        echo json_encode($data);
        die;
    }

///获取支付链接 old
   /* public function get_pay_url($pay_sn = '')
    {
        $return = $_GET['return'];
        $pay_sn = $_GET['pay_sn'];
        //购买开关
        $buy_switch = M('sys_param')->where(array('param_code' => 'buy_switch'))->getField('param_value');
        if (empty($buy_switch)) {
            $data['status'] = 0;
            $data['error'] = '管理员已关闭交易';
            if ($return == 1) {
                return $data;
            }
            echo json_encode($data);
            die;
        }
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger') === false) {
            $data['status'] = 0;
            $data['error'] = '请在微信上打开支付';
            if ($return == 1) {
                return $data;
            }
            echo json_encode($data);
            die;
        }
        $payment_code = 'wxpay';
        $model_payment = D('Mallpayment');
        $result = $model_payment->productBuy($pay_sn, $payment_code, $_SESSION['member']['uid']);
        if (!empty($result['error'])) {
            $data['status'] = 0;
            $data['error'] = $result['error'];
            if ($return == 1) {
                return $data;
            }
            echo json_encode($data);
            die;
        }
        $order_pay_info = $result['order_pay_info'];
        $payment_info = $result['payment_info'];
        $user_open_id = $_SESSION['user_open_id'];
        if (empty($user_open_id)) {
            $data['status'] = 0;
            $data['error'] = "拉起支付失败，请刷新页面再试";
            session('user_open_error', null);
            if ($return == 1) {
                return $data;
            }
            echo json_encode($data);
            die;
        }
        $url = 'pay_sn=' . $order_pay_info['pay_sn']
            . '&pay_amount=' . $order_pay_info['pay_amount']
            //    .'&subject='.$order_pay_info['subject']
            . '&openid=' . $user_open_id;
        //$url=urlencode($url);
        $url = "http://" . $_SERVER['HTTP_HOST'] . '/api/payment/wpay/get_pay_jsapi.php?' . $url;
        $data['status'] = 1;
        $data['pay_url'] = $url;
        if ($return == 1) {
            return $data;
        }
        echo json_encode($data);
        die;
    }*/

    ///支付宝
    public function go_alipay_pay(){
        $return_data['status']=0;
        $order_sn=I('order_sn');
        $pay_name ='alipay';
        //购买开关
        $buy_switch=M('sys_param')->where(array('param_code'=>'buy_switch'))->getField('param_value');
        if(empty($buy_switch)){
            $return_data['error']='管理员已关闭交易';
            echo json_encode($return_data);die;
        }
        $model_order = D('Mallorder');
        $save_data=array();
        $save_data['pay_name']=$pay_name;//改变订单 支付方式
        $res=M('g_order_info')->where(array('order_sn'=>$order_sn))->save($save_data);
        if($res===false){
            $return_data['error']='支付错误，请刷新页面重试';
            $return_data['status']=0;
            echo json_encode($return_data);die;
        }
        //在线支付
        $condition = array();
        $condition['order_sn'] = $order_sn;
        $condition['pay_status'] = '0';// 支付状态；0，未付款；1，付款中 ；2，已付款
        $order_list = $model_order->getOrderList($condition,'','*');

        if (empty($order_list)) {
            $return_data['error']="该订单不存在";
            echo json_encode($return_data);die;
        }
        //计算本次需要在线支付的订单总金额
        $time=time();
        $pay_amount = 0;
        $offline_money=0;
        foreach ($order_list as $order_info) {
            ///减去余额支付部分 减去折扣部分
            ///折扣是否过期
            if($order_info['discount_start_time']<=$time && $order_info['discount_end_time']>=$time){
                $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['first_discount'])  - floatval($order_info['surplus']) - floatval($order_info['discount']));
            }else{
                $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['first_discount']) - floatval($order_info['surplus']));
            }
        }
        //如果为空，说明已经都支付过了或已经取消或者是价格为0的商品订单，全部返回
        if (empty($pay_amount)) {
            $return_data['error']="订单金额为0，不需要支付";
            echo json_encode($return_data);die;
        }
        $return_data['need_pay']=1;///需要支付 1  不需要支付0
        $return_data['status']=1;
        echo json_encode($return_data);die;

    }
    public function upgrade_level($order_sn){
        //g_order_info
        //member_level_order
        //member
        $where['order_sn']=$order_sn;
        $order_info=M('g_order_info')->where($where)->find();
        if($order_info['is_upgrade']){
            $where1['id']=$order_sn;
            $level_order_info=M('member_level_order')->where($where1)->find();
            if (!empty($level_order_info)){
                M('member_level_order')->where($where1)->setField('pay_status','1');
                $where2['id']=$order_info['user_id'];
                $member_data=array('member_vip_type'=>$level_order_info['levelId'],'member_vip_order'=>$level_order_info['levelId'],'vip_time'=>time());
                M('member')->where($where2)->save($member_data);
            }else{
                return  "该订单不存在";
            }
        }
    }

}